<div class="viewer-container">
  <!-- Header -->
  <div class="flex align-items-center justify-content-between mb-4">
    <div class="flex align-items-center gap-2 header-title-container">
      <h1>System Events</h1>
      <p-tag
        [severity]="isConnected() ? 'success' : 'danger'"
        [value]="isConnected() ? 'Connected' : 'Disconnected'"
        [pTooltip]="isConnected() ? 'Connected to event hub' : 'Attempting to reconnect...'"
        tooltipPosition="right"
        styleClass="status-tag"
      ></p-tag>
    </div>
    <div class="item-controls flex align-items-center gap-2">
      <button
        pButton
        icon="pi pi-download"
        class="p-button-rounded p-button-text"
        (click)="exportEvents($event)"
        pTooltip="Export events"
        tooltipPosition="left"
      ></button>
      <button
        pButton
        icon="pi pi-copy"
        class="p-button-rounded p-button-text"
        (click)="copyEvents()"
        pTooltip="Copy events"
        tooltipPosition="left"
      ></button>
      <button
        pButton
        icon="pi pi-refresh"
        class="p-button-rounded p-button-text"
        (click)="refresh()"
        pTooltip="Refresh events"
        tooltipPosition="left"
      ></button>
    </div>
  </div>

  <!-- Events Card -->
  <p-card styleClass="dashboard-card h-full viewer-card">
    <ng-template pTemplate="header">
      <div class="flex align-items-center justify-content-between border-bottom-1 surface-border w-full">
        <div class="header-title-container w-full">
          <!-- Filters Section -->
          <div class="filter-container p-3 w-full">
            <p-toolbar styleClass="filter-toolbar">
              <ng-template pTemplate="start">
                <div class="flex align-items-center gap-2 flex-wrap filter-inputs-container mb-2">
                  <!-- Search Filter -->
                  <input
                    type="text"
                    pInputText
                    [ngModel]="searchFilter()"
                    (input)="onSearchChange($event)"
                    placeholder="Search events"
                    [disabled]="!isConnected()"
                    class="search-input"
                  />

                  <!-- Severity Filter -->
                  <p-select
                    [options]="severities()"
                    [ngModel]="severityFilter()"
                    placeholder="Severity"
                    [showClear]="true"
                    (onChange)="onSeverityFilterChange($event.value)"
                    styleClass="severity-dropdown fixed-width-dropdown"
                    [disabled]="!isConnected()"
                  >
                  </p-select>

                  <!-- Event Type Filter -->
                  <p-select
                    [options]="eventTypes()"
                    [ngModel]="eventTypeFilter()"
                    placeholder="Event type"
                    [showClear]="true"
                    (onChange)="onEventTypeFilterChange($event.value)"
                    styleClass="event-type-dropdown fixed-width-dropdown"
                    [disabled]="!isConnected()"
                  >
                  </p-select>

                  <!-- Date Range Filters -->
                  <div class="flex gap-2">
                    <p-datePicker
                    [ngModel]="fromDate()"
                    (ngModelChange)="fromDate.set($event); onDateFilterChange()"
                    dateFormat="yy-mm-dd"
                    [showTime]="true"
                    [timeOnly]="false"
                    placeholder="Start date"
                    [showClear]="true"
                    [showIcon]="true"
                    [disabled]="!isConnected()"
                    styleClass="date-filter"
                  ></p-datePicker>

                  <p-datePicker
                    [ngModel]="toDate()"
                    (ngModelChange)="toDate.set($event); onDateFilterChange()"
                    dateFormat="yy-mm-dd"
                    [showTime]="true"
                    [timeOnly]="false"
                    placeholder="End date"
                    [showClear]="true"
                    [showIcon]="true"
                    [disabled]="!isConnected()"
                    styleClass="date-filter"
                  ></p-datePicker>
                  </div>
                </div>
              </ng-template>
              <ng-template pTemplate="end">
                <div class="filter-actions-container flex flex-grow-1 justify-content-end align-items-end">
                  <div class="filter-actions-wrapper">
                    <div class="filter-stats" *ngIf="isConnected() && filteredEvents().length > 0">
                      <span class="text-sm text-color-secondary">
                        Showing {{ filteredEvents().length }} of {{ events().length }} events
                      </span>
                    </div>
                    <!-- Clear Filters Button -->
                    <button
                      pButton
                      icon="pi pi-filter-slash"
                      label="Clear Filters"
                      class="p-button-outlined ml-2 clear-filters-btn"
                      (click)="clearFilters()"
                      [disabled]="
                        !isConnected() ||
                        (!severityFilter() && !eventTypeFilter() && !searchFilter() && !fromDate() && !toDate())
                      "
                    ></button>
                  </div>
                </div>
              </ng-template>
            </p-toolbar>
          </div>
        </div>
      </div>
    </ng-template>

      <!-- Console-style Events View -->
      <div class="viewer-console" #eventsConsole>
        <!-- Events List -->
        <div class="items-list" *ngIf="filteredEvents().length > 0; else emptyEvents">
          <div *ngFor="let event of filteredEvents(); let i = index" class="item-entry" [id]="'event-' + i">
            <!-- Event Entry Header - only expandable if has data or tracking ID -->
            <div
              class="item-entry-header"
              [class.expandable]="event.data || event.trackingId"
              (click)="event.data || event.trackingId ? toggleEventExpansion(i, $event) : null"
            >
              <!-- Actions (Copy button at start) -->
              <div class="item-actions item-actions-start">
                <button
                  pButton
                  icon="pi pi-copy"
                  class="p-button-rounded p-button-text p-button-sm"
                  (click)="copyEventEntry(event, $event)"
                  pTooltip="Copy event"
                ></button>
              </div>

              <!-- Timestamp -->
              <div class="item-timestamp">
                <span class="item-date">{{ event.timestamp | date : "yyyy-MM-dd" }}</span>
                <span class="item-time">{{ event.timestamp | date : "HH:mm:ss.SSS" }}</span>
              </div>

              <!-- Severity Tag -->
              <div class="item-severity">
                <p-tag [severity]="getSeverity(event.severity)" [value]="event.severity" [rounded]="true"></p-tag>
              </div>

              <!-- Event Type -->
              <div class="item-type">
                <span class="item-type-badge">{{ event.eventType }}</span>
              </div>

              <!-- Message -->
              <div class="item-message">
                {{ event.message }}
              </div>

              <!-- Tracking ID (if exists) -->
              <div class="event-tracking" *ngIf="event.trackingId">
                <p-tag
                  [value]="event.trackingId"
                  severity="secondary"
                  [rounded]="true"
                  styleClass="tracking-tag"
                  [pTooltip]="'Tracking ID: ' + event.trackingId"
                ></p-tag>
              </div>

              <!-- Dropdown button (only for events with data or tracking ID) -->
              <div class="item-actions" *ngIf="event.data || event.trackingId">
                <button
                  pButton
                  [icon]="expandedEvents[i] ? 'pi pi-chevron-up' : 'pi pi-chevron-down'"
                  class="p-button-rounded p-button-text p-button-sm"
                  (click)="toggleEventExpansion(i, $event)"
                  pTooltip="Toggle details"
                ></button>
              </div>
            </div>

            <!-- Event Details (Expandable) -->
            <div class="item-details" *ngIf="expandedEvents[i]">
              <!-- Data -->
              <div class="item-data" *ngIf="event.data">
                <div class="data-label">Data:</div>
                <pre class="data-content" *ngIf="isValidJson(event.data)">{{ formatJsonData(event.data) }}</pre>
                <div class="data-content" *ngIf="!isValidJson(event.data)">{{ event.data }}</div>
              </div>

              <!-- Tracking Information -->
              <div class="item-metadata" *ngIf="event.trackingId">
                <div class="metadata-item">
                  <span class="metadata-label">Tracking ID:</span>
                  <span class="metadata-value">{{ event.trackingId }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Empty State -->
        <ng-template #emptyEvents>
          <div class="empty-items">
            <div class="empty-message">
              <i class="pi pi-inbox empty-icon"></i>
              <!-- Check connection status first -->
              <div *ngIf="!isConnected() && !loading(); else connectedState">
                <div class="flex flex-column align-items-center gap-3">
                  <div class="empty-text">Not connected to server</div>
                  <p>Check your network connection and try again</p>
                  <!-- No spinner here - we're not actively loading anything -->
                </div>
              </div>

              <!-- Connected state - either loading or no events -->
              <ng-template #connectedState>
                <div *ngIf="loading(); else noEvents">
                  <div class="empty-text">Loading events...</div>
                  <p-progressSpinner
                    styleClass="w-3rem h-3rem"
                    strokeWidth="4"
                    fill="var(--surface-ground)"
                    animationDuration=".5s"
                  ></p-progressSpinner>
                </div>

                <ng-template #noEvents>
                  <div class="empty-text">No events found</div>
                  <p>Try adjusting your filters</p>
                </ng-template>
              </ng-template>
              <!-- Removed the redundant disconnectedMessage template -->
            </div>
          </div>
        </ng-template>
      </div>

      <div class="card-footer mt-3">
        <!-- Pagination Controls -->
        <div class="pagination-container p-3 border-top-1 surface-border">
          <p-paginator
            [rows]="pageSize()"
            [totalRecords]="totalRecords()"
            [rowsPerPageOptions]="[25, 50, 100, 250]"
            (onPageChange)="onPageChange($event)"
            [showCurrentPageReport]="true"
            currentPageReportTemplate="{first} to {last} of {totalRecords} events"
            [alwaysShow]="true"
            styleClass="events-paginator"
          ></p-paginator>
        </div>
      </div>
  </p-card>

  <!-- Export Menu -->
  <p-menu #exportMenu [popup]="true" [model]="exportMenuItems" appendTo="body"></p-menu>
</div>
